package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.TimeUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xinchunting on 17-9-6.
 */
@RestController
public class APIUserProfitController extends BaseController {

        @Autowired
        private UserProfitService userProfitService;
        @Autowired
        private SysUserService sysUserService;
        @Autowired
        private UserMembersService userMembersService;
        @Autowired
        private OrderProdService orderProdService;
        @Autowired
        private OrderService orderService;
        @Autowired
        private CompanyService companyService;
        @Autowired
        private GoodsService goodsService;
        @Autowired
        private LocalOrderService localOrderService;
        @Autowired
        private UserRewardService userRewardService;
        @Autowired
        private WalletService walletService;
        @Autowired
        private WalletCompanyService walletCompanyService;



    /**
     * @api {get} /api/admin/userProfit/all 后台管理-订单管理-个人钱包流水
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/userProfit/all
     *
     * @apiName findUserProfitAll
     * @apiGroup UserProfit
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiParam {long} stime 开始时间.
     * @apiParam {long} etime 结束时间.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "amount": 100,
     *               "consumerId": 0,
     *               "ctime": 1503990865654,
     *               "mtime": 1503990865654,
     *               "orderId": 0,
     *               "orderSn": "-1",
     *               "orderType": -1,
     *               "profitId": 648,
     *               "remark": "",
     *               "rstatus": 0,
     *               "userBalance": 0,
     *               "userId": 1,
     *               "userProfit": -100
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/userProfit/all"
     *  }
     */
    @RequestMapping(value = "/api/admin/userProfit/all")
    public String findUserProfitAll(UserProfit userProfit, int page) {
        userProfit.setPage(page);
        List<UserProfitVO> userProfitVOS= new ArrayList<>();
        List<UserProfit> userProfits=userProfitService.selectForPage(userProfit);
        for (UserProfit up:userProfits){
            UserProfitVO userProfitVO = new UserProfitVO();
            BeanUtils.copyProperties(up,userProfitVO);
            SysUser sysUser=sysUserService.selectByPK(up.getConsumerId());
            if (ObjectUtils.isEmpty(sysUser)){
                userProfitVO.setNickname("");
            }else {
                userProfitVO.setNickname(sysUser.getNickname());
            }
            userProfitVOS.add(userProfitVO);
        }
        MsgOut o = MsgOut.success(userProfitVOS);
        o.setRecords(userProfit.getRecords());
        o.setTotal(userProfit.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/admin/usersProfit 后台管理-订单管理-个人钱包-详情
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/usersProfit
     *
     * @apiName findUserProfitList
     * @apiGroup UserProfit
     *
     * @apiParam {int} userId 用户Id.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "amount": 20000,
     *                   "consumerId": 6249,
     *                   "ctime": 1499520863095,
     *                   "mtime": 1499520863095,
     *                   "orderId": 346,
     *                   "orderSn": "20170708213402489l6249",
     *                   "orderType": 4,
     *                   "profitId": 587,
     *                   "remark": "梁鹤平",
     *                   "rstatus": 0,
     *                   "userBalance": 0,
     *                   "userId": 6249,
     *                   "userProfit": 80
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/usersProfit"
     *  }
     */
    @RequestMapping(value = "/api/admin/usersProfit")
    public String findUserProfitList(UserProfit userProfit, int page) {
        userProfit.setPage(page);
        List<UserProfitVO> userProfitVOList = new ArrayList<>();
        List<UserProfit> list = userProfitService.selectForPage(userProfit);
        for (UserProfit up : list) {
            UserProfitVO userProfitVO = new UserProfitVO();
            BeanUtils.copyProperties(up, userProfitVO);
            if (userProfitVO.getUserProfit() < 0) {
                userProfitVO.setUserExpenses(userProfitVO.getUserProfit());
                userProfitVO.setUserProfit(0);
            }
            userProfitVO.setNickname(sysUserService.selectByPK(up.getConsumerId()).getNickname());
            userProfitVOList.add(userProfitVO);
        }
        MsgOut o = MsgOut.success(userProfitVOList);
        o.setRecords(userProfit.getRecords());
        o.setTotal(userProfit.getTotal());
        return this.renderJson(o);
    }

    /**
     * 个人中心   资产管理明细
     * @param userProfit
     * @param page
     * @return
     */
    @RequestMapping(value = "/api/wap/usersProfit/page")
    public String UserProfitList(UserProfit userProfit, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        userProfit.setPage(page);
        List<UserProfitVO> userProfitVOList = new ArrayList<>();
        List<UserProfit> list = userProfitService.selectForPage(userProfit);
        for (UserProfit up : list) {
            UserProfitVO userProfitVO = new UserProfitVO();
            BeanUtils.copyProperties(up, userProfitVO);
            userProfitVO.setRemark(sysUserService.selectByPK(up.getConsumerId()).getNickname());
            userProfitVOList.add(userProfitVO);
        }
        MsgOut o = MsgOut.success(userProfitVOList);
        o.setRecords(userProfit.getRecords());
        o.setTotal(userProfit.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {get}/api/admin/order/profit 后台管理-订单管理-商城订单-返利详情
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/order/profit
     *
     * @apiName findOrderProfit
     * @apiGroup UserProfit
     *
     * @apiParam {string} orderSn 订单编号.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "amount": 20000,
     *                   "consumerId": 6249,
     *                   "ctime": 1499520863095,
     *                   "mtime": 1499520863095,
     *                   "orderId": 346,
     *                   "orderSn": "20170708213402489l6249",
     *                   "orderType": 4,
     *                   "profitId": 587,
     *                   "remark": "梁鹤平",
     *                   "rstatus": 0,
     *                   "userBalance": 0,
     *                   "userId": 6249,
     *                   "userProfit": 80
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/order/profit"
     *  }
     */
    @RequestMapping(value = "/api/admin/order/profit")
    public String findOrderProfit(UserProfit userProfit) {
        List<UserProfit> list;
        userProfit.setOrderBy("profit_id");
        list = userProfitService.select(userProfit);
        for (UserProfit user : list) {
            user.setRemark(sysUserService.selectByPK(user.getUserId()).getNickname());
            //受益者类型
            if (ObjectUtils.isEmpty(userMembersService.selectByPK(user.getUserId()))) {

                user.setRstatus((byte) 100);
            } else {

                user.setRstatus(userMembersService.selectByPK(user.getUserId()).getMemberType());
            }
        }
        MsgOut o = MsgOut.success(list);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/admin/localOrder/Profit后台管理-订单管理-扫码订单-返利详情
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/localOrder/Profit
     *
     * @apiName findLocalOrderProfit
     * @apiGroup UserProfit
     *
     *  @apiParam {string} orderSn 订单编号.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "amount": 20000,
     *                   "consumerId": 6249,
     *                   "ctime": 1499520863095,
     *                   "mtime": 1499520863095,
     *                   "orderId": 346,
     *                   "orderSn": "20170708213402489l6249",
     *                   "orderType": 4,
     *                   "profitId": 587,
     *                   "remark": "梁鹤平",
     *                   "rstatus": 0,
     *                   "userBalance": 0,
     *                   "userId": 6249,
     *                   "userProfit": 80
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/localOrder/Profit"
     *  }
     */
    @RequestMapping(value = "/api/admin/localOrder/Profit")
    public String findLocalOrderProfit(UserProfit userProfit) {
        List<UserProfit> list;
        List<UserProfit> users = new ArrayList<>();
        userProfit.setOrderBy("profit_id");
        list = userProfitService.select(userProfit);
        for (UserProfit user : list) {
            user.setRemark(sysUserService.selectByPK(user.getUserId()).getNickname());
            if (ObjectUtils.isEmpty(userMembersService.selectByPK(user.getUserId()))) {
                user.setRstatus((byte) 100);
            } else {
                user.setRstatus(userMembersService.selectByPK(user.getUserId()).getMemberType());
            }
            users.add(user);
        }
        MsgOut o = MsgOut.success(users);
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/admin/usersProfit/sum 后台管理-订单管理-个人钱包-详情-总计
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/usersProfit/sum
     *
     * @apiName findUserProfitSum
     * @apiGroup UserProfit
     *
     *  @apiParam {int} userId 用户Id.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "amount": 0,
     *               "remark": "总计",
     *               "userExpenses": -146400,
     *               "userProfit": 146400,
     *               "userScoreExpenses": 0
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/usersProfit/sum"
     *  }
     */
//    @RequestMapping(value = "/api/admin/usersProfit/sum")
//    public String findUserProfitSum(UserProfit userProfit) {
//        if (ObjectUtils.isEmpty(userProfit)) {
//            return this.renderJson(MsgOut.error("参数错误"));
//        }
//        List<UserProfit> list = userProfitService.select(userProfit);
//        int userProfitNum = 0;
//        int userExpensesNum = 0;
//        int userScoreNum = 0;
//        int userScoreExpensesNum = 0;
//        for (UserProfit up : list) {
//            UserProfitVO userProfitVO = new UserProfitVO();
//            BeanUtils.copyProperties(up, userProfitVO);
//            if (userProfitVO.getUserProfit() < 0) {
//                if (userProfitVO.getOrderType() == -3) {
//                    userScoreExpensesNum += userProfitVO.getUserProfit();
//                } else {
//                    userExpensesNum += userProfitVO.getUserProfit();
//                }
//            } else {
//                if (userProfitVO.getOrderType() == 3 || userProfitVO.getOrderType() == 4 || userProfitVO.getOrderType() == 5) {
//                    userScoreNum += userProfitVO.getUserProfit();
//                } else {
//                    userProfitNum += userProfitVO.getUserProfit();
//                }
//            }
//        }
//        UserProfitVO num = new UserProfitVO();
//        num.setUserProfit(userProfitNum);
//        num.setUserExpenses(userExpensesNum);
//        num.setAmount(userScoreNum);
//        num.setUserScoreExpenses(userScoreExpensesNum);
//        num.setRemark("总计");
//        MsgOut o = MsgOut.success(num);
//        return this.renderJson(o);
//    }

    /**
     * @api {get} /api/admin/userProfit/excel/{userId} 后台管理-订单管理-个人钱包-excel导出
     * @apiSampleRequest /api/admin/userProfit/excel/{userId}
     * @apiVersion 0.1.0
     * @apiName adminUserProfitExcel
     * @apiGroup UserProfit
     *
     * @apiParam {long} userId 用户ID.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/userProfit/excel/{userId}"
     *  }
     */

    @RequestMapping(value = "/api/admin/userProfit/excel/{userId}")
    public void adminUserProfitExcel(@PathVariable("userId") Long userId) {
        //SHEET1
        Wallet wallet;
        SysUser sysUser;
        List<SysUser> users = new ArrayList<>();
        wallet = walletService.selectByPK(userId);
        sysUser = sysUserService.selectByPK(userId);
        sysUser.setEmail(wallet.getUserBalance().toString());
        sysUser.setPhone(wallet.getUserAmount().toString());
        sysUser.setPosition(wallet.getUserScore().toString());
        sysUser.setDepartment(wallet.getUserScoreTotal().toString());
        sysUser.setHeadimgurl(TimeUtils.getDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_LINE, wallet.getCtime()));
        users.add(sysUser);


        UserProfit userProfit = new UserProfit();
        SysUser sysUser1;
        userProfit.setUserId(userId);
        sysUser1 = sysUserService.selectByPK(userId);
        List<UserProfitVO> userProfitVOList = new ArrayList<>();
        List<UserProfit> where = userProfitService.select(userProfit);
        int sumUserProfit = 0;
        int sunUserExpenses = 0;
        for (UserProfit up : where) {
            UserProfitVO userProfitVO = new UserProfitVO();
            BeanUtils.copyProperties(up, userProfitVO);
            userProfitVO.setRemark(TimeUtils.getDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_LINE, up.getCtime()));
            if (userProfitVO.getUserProfit() < 0) {
                sunUserExpenses += userProfitVO.getUserProfit();
                userProfitVO.setUserExpenses(userProfitVO.getUserProfit());
                userProfitVO.setUserProfit(0);
            } else {
                sumUserProfit += userProfitVO.getUserProfit();
                userProfitVO.setUserExpenses(0);
            }
            switch (up.getOrderType()) {
                case 0:
                    userProfitVO.setStrordertrpe("商城供货商订单返利");
                    break;
                case 1:
                    userProfitVO.setStrordertrpe("地面店扫码订单返利");
                    break;
                case 2:
                    userProfitVO.setStrordertrpe("商城微商订单返利");
                    break;
                case 3:
                    userProfitVO.setStrordertrpe("地面店扫码订单返积分");
                    break;
                case 4:
                    userProfitVO.setStrordertrpe("商城微商订单返积分");
                    break;
                case 5:
                    userProfitVO.setStrordertrpe("点餐订单返积分");
                    break;
                case 6:
                    userProfitVO.setStrordertrpe("点餐订单返利");
                    break;
                case 7:
                    userProfitVO.setStrordertrpe("快转返利");
                    break;
                case 8:
                    userProfitVO.setStrordertrpe("快省返利");
                    break;
                case 9:
                    userProfitVO.setStrordertrpe("快签返利");
                    break;
                case 10:
                    userProfitVO.setStrordertrpe("快飞返利");
                    break;
                case 11:
                    userProfitVO.setStrordertrpe("快推返利");
                    break;
                case 12:
                    userProfitVO.setStrordertrpe("快点返利");
                    break;
                case -1:
                    userProfitVO.setStrordertrpe("提现");
                    break;
                case -2:
                    userProfitVO.setStrordertrpe("退款扣除奖励");
                    break;
            }
            UserProfitVO sumupvo = new UserProfitVO();
            sumupvo.setUserProfit(sumUserProfit);
            sumupvo.setUserExpenses(sunUserExpenses);
            sumupvo.setStrcompanytype("总计");
            userProfitVOList.add(userProfitVO);
            userProfitVOList.add(sumupvo);
        }
        HttpServletResponse response = this.getResponse();
        //设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel");        //改成输出excel文件
        String fileName = sysUser1.getNickname();
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

        //创建工作簿并发送到浏览器
        try {
            //创键Excel表格中的第一个表,命名为"第一页"
            WritableWorkbook book = Workbook.createWorkbook(response.getOutputStream());
//第一sheet
            WritableSheet sheet = book.createSheet("订单详情", 0);
            //设置该单元格的表头
            List<String> keys = new ArrayList<>();
            keys.add("ID");
            keys.add("名字");
            keys.add("余额");
            keys.add("总额");
            keys.add("积分");
            keys.add("总积分");
            keys.add("时间");
            // 添加标题
            for (int x = 0; x < keys.size(); x++) {
                sheet.addCell((WritableCell) new Label(x, 0, keys.get(x)));
            }
            // 添加数据
            for (int y = 0; y < users.size(); y++) {
                sheet.addCell(new Label(0, y + 1, users.get(y).getId().toString()));
                sheet.addCell(new Label(1, y + 1, users.get(y).getNickname()));
                sheet.addCell(new Label(2, y + 1, users.get(y).getEmail()));
                sheet.addCell(new Label(3, y + 1, users.get(y).getPhone()));
                sheet.addCell(new Label(4, y + 1, users.get(y).getPosition()));
                sheet.addCell(new Label(5, y + 1, users.get(y).getDepartment()));
                sheet.addCell(new Label(6, y + 1, users.get(y).getHeadimgurl()));
            }
//第二个sheet
            WritableSheet sheet2 = book.createSheet("返利详情", 1);

            //设置该单元格的表头
            List<String> keys2 = new ArrayList<>();
            keys2.add("流水ID");
            keys2.add("订单ID");
            keys2.add("订单SN");
            keys2.add("订单类型");
            keys2.add("收益");
            keys2.add("支出");
            keys2.add("余额");
            keys2.add("账户余额");
            keys2.add("时间");
            // 添加标题
            for (int x = 0; x < keys2.size(); x++) {
                sheet2.addCell((WritableCell) new Label(x, 0, keys2.get(x)));
            }
            // 添加数据
            for (int y = 0; y < userProfitVOList.size(); y++) {
                sheet2.addCell(new Label(0, y + 1, userProfitVOList.get(y).getProfitId().toString()));
                sheet2.addCell(new Label(1, y + 1, userProfitVOList.get(y).getOrderId().toString()));
                sheet2.addCell(new Label(2, y + 1, userProfitVOList.get(y).getOrderSn()));
                sheet2.addCell(new Label(3, y + 1, userProfitVOList.get(y).getStrordertrpe()));
                sheet2.addCell(new Label(4, y + 1, userProfitVOList.get(y).getUserProfit().toString()));
                sheet2.addCell(new Label(5, y + 1, userProfitVOList.get(y).getUserExpenses().toString()));
                sheet2.addCell(new Label(6, y + 1, userProfitVOList.get(y).getUserBalance().toString()));
                sheet2.addCell(new Label(7, y + 1, userProfitVOList.get(y).getAmount().toString()));
                sheet2.addCell(new Label(8, y + 1, userProfitVOList.get(y).getRemark()));
            }

            // 写入数据并关闭文件
            book.write();
            book.close();
        } catch (Exception e) {

        }
    }




















        /**
         * @api {get} /api/admin/orderProd/all 后台管理-订单管理-商家钱包流水
         * @apiVersion 0.1.0
         * @apiSampleRequest /api/admin/orderProd/all
         *
         * @apiName findOrderProdAll
         * @apiGroup UserProfit
         *
         * @apiParam {int} page 第几页.
         * @apiParam {int} rows 每页条数.
         * @apiParam {long} stime 开始时间.
         * @apiParam {long} etime 结束时间.
         *
         * @apiSuccess {int} code 接口返回状态码.
         * @apiSuccess {String} msg  接口返回信息.
         * @apiSuccess {Object} data  接口返回数据.
         *
         * @apiSuccessExample Success-Response:
         *     HTTP/1.1 200 OK
         *
         *    {
         *       "code":0,
         *       "data":[
         *           {
         *               "companyBalance": 0,
         *               "ctime": 1503982704028,
         *               "giveScore": 0,
         *               "giveType": 0,
         *               "goodsAttrLinkId": "0",
         *               "goodsAttrValues": "",
         *               "goodsGetType": 0,
         *               "goodsId": 1832,
         *               "goodsName": "快省-消费增值",
         *               "goodsNumber": 1,
         *               "goodsPayType": 0,
         *               "goodsProviderId": 1,
         *               "goodsProviderType": 127,
         *               "goodsRealPrice": 0,
         *               "goodsScore": 0,
         *               "goodsScreenPrice": 10000,
         *               "goodsThum": "http://static.ruitaowang.com/attached/file/20170609/20170609141826_47.png",
         *               "logisticsId": 0,
         *               "logisticsName": "",
         *               "logisticsSn": "",
         *               "memberPrice": 0,
         *               "mtime": 1503982704028,
         *               "orderId": 378,
         *               "prodId": 381,
         *               "remark": "0",
         *               "rstatus": 0,
         *               "selfSupport": false,
         *               "xpPrice": 0
         *           }
         *       ],
         *       "msg":"操作成功啦",
         *       "records":5,
         *       "title":"成功",
         *       "total":1,
         *       "type":"SUCCESS"
         *    }
         *
         * @apiError InternalServerError.
         *
         * @apiErrorExample Error-Response:
         *     HTTP/1.1 500 Internal Server Error
         *  {
         *      "timestamp":1504064947603,
         *      "status":500,
         *      "error":"Internal Server Error",
         *      "exception":"java.lang.ArithmeticException",
         *      "message":"/ by zero",
         *      "path":"/api/admin/orderProd/all"
         *  }
         */

    @RequestMapping(value = "/api/admin/orderProd/all")
    public String findOrderProdAll(OrderProd orderProd, int page) {
//        List out =new ArrayList();
//        Order order =new Order();
//        orderService.select(order);
        orderProd.setPage(page);
        List<OrderProd> orderProds=orderProdService.timeForPage(orderProd);
//        for (OrderProd where:orderProds){
//            if (orderService.selectByPK(where.getOrderId()).getPayStatus() == 1){
//                out.add(where);
//            }
//        }
        MsgOut o = MsgOut.success(orderProds);
        o.setRecords(orderProd.getRecords());
        o.setTotal(orderProd.getTotal());
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/admin/orderProd/detail 后台管理-订单管理-商家钱包-订单详情
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/orderProd/detail
     *
     * @apiName findOrderProdDetail
     * @apiGroup UserProfit
     *
     * @apiParam {int} companyId 商户ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "companyBalance": 0,
     *               "ctime": 1503982704028,
     *               "giveScore": 0,
     *               "giveType": 0,
     *               "goodsAttrLinkId": "0",
     *               "goodsAttrValues": "",
     *               "goodsGetType": 0,
     *               "goodsId": 1832,
     *               "goodsName": "快省-消费增值",
     *               "goodsNumber": 1,
     *               "goodsPayType": 0,
     *               "goodsProviderId": 1,
     *               "goodsProviderType": 127,
     *               "goodsRealPrice": 0,
     *               "goodsScore": 0,
     *               "goodsScreenPrice": 10000,
     *               "goodsThum": "http://static.ruitaowang.com/attached/file/20170609/20170609141826_47.png",
     *               "logisticsId": 0,
     *               "logisticsName": "",
     *               "logisticsSn": "",
     *               "memberPrice": 0,
     *               "mtime": 1503982704028,
     *               "orderId": 378,
     *               "prodId": 381,
     *               "remark": "0",
     *               "rstatus": 0,
     *               "selfSupport": false,
     *               "xpPrice": 0
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/orderProd/detail"
     *  }
     */
    @RequestMapping(value = "/api/admin/orderProd/detail")
    public String findOrderProdDetail(Long companyId) {
        OrderProd orderProd = new OrderProd();
        orderProd.setGoodsProviderId(companyId);
        List<OrderProd> out = new ArrayList<>();
        List<OrderProd> users = orderProdService.select(orderProd);
        for (OrderProd op : users) {
            if (orderService.selectByPK(op.getOrderId()).getPayStatus() == 1) {
                op.setGoodsPayType(goodsService.selectByPK(op.getGoodsId()).getGoodsPayType());
                op.setGiveType(orderService.selectByPK(op.getOrderId()).getPayStatus());
                op.setGoodsProviderType(companyService.selectByPK(op.getGoodsProviderId()).getCompanyType());
                out.add(op);
            }
        }
        MsgOut o = MsgOut.success(out);
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/admin/localOrders/detail 后台管理-订单管理-商家钱包-扫码订单详情
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/localOrders/detail
     *
     * @apiName findLocalOrdersDetail
     * @apiGroup UserProfit
     *
     * @apiParam {int} companyId 商户ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "companyBalance": 0,
     *               "ctime": 1503982704028,
     *               "giveScore": 0,
     *               "giveType": 0,
     *               "goodsAttrLinkId": "0",
     *               "goodsAttrValues": "",
     *               "goodsGetType": 0,
     *               "goodsId": 1832,
     *               "goodsName": "快省-消费增值",
     *               "goodsNumber": 1,
     *               "goodsPayType": 0,
     *               "goodsProviderId": 1,
     *               "goodsProviderType": 127,
     *               "goodsRealPrice": 0,
     *               "goodsScore": 0,
     *               "goodsScreenPrice": 10000,
     *               "goodsThum": "http://static.ruitaowang.com/attached/file/20170609/20170609141826_47.png",
     *               "logisticsId": 0,
     *               "logisticsName": "",
     *               "logisticsSn": "",
     *               "memberPrice": 0,
     *               "mtime": 1503982704028,
     *               "orderId": 378,
     *               "prodId": 381,
     *               "remark": "0",
     *               "rstatus": 0,
     *               "selfSupport": false,
     *               "xpPrice": 0
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/localOrders/detail"
     *  }
     */
    @RequestMapping(value = "/api/admin/localOrders/detail")
    public String findLocalOrdersDetail(Long companyId) {
        List<LocalOrder> list;
        LocalOrder localOrders = new LocalOrder();
        localOrders.setCompanyId(companyId);
        list = localOrderService.select(localOrders);
        if (!ObjectUtils.isEmpty(list)) {
            for (LocalOrder localOrder : list) {
                localOrder.setRemark(sysUserService.selectByPK(localOrder.getUserId()).getNickname());
            }
        }
        MsgOut o = MsgOut.success(list);
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/admin/localOrders/detail 后台管理-订单管理-商家钱包-提现详情
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/localOrders/detail
     *
     * @apiName findLocalOrdersDetail
     * @apiGroup UserProfit
     *
     * @apiParam {int} companyId 商户ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "amount": 16000,
     *               "ctime": 1499522051439,
     *               "idCard": "32110296507292817",
     *               "mtime": 1500016407959,
     *               "paymentNo": "0",
     *               "realName": "梁鹤平",
     *               "remark": "",
     *               "rewardId": 44,
     *               "rewardType": 1,
     *               "rstatus": 1,
     *               "userId": 62883
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/localOrders/detail"
     *  }
     */
    @RequestMapping("/api/admin/company/rewards")
    public String list(Long companyId, int page) {
        if (ObjectUtils.isEmpty(companyId)) {
            return this.renderJson(MsgOut.error("参数错误"));
        }
        Company company = companyService.selectByPK(companyId);
        UserReward userReward = new UserReward();
        userReward.setUserId(company.getUserId());
        userReward.setRewardType((byte) 1);
        userReward.setPage(page);
        MsgOut o = MsgOut.success(userRewardService.selectForPage(userReward));
        o.setRecords(userReward.getRecords());
        o.setTotal(userReward.getTotal());
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/admin/orderProd/sum 后台管理-订单管理-商家钱包-详情-总计
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/orderProd/sum
     *
     * @apiName findOrderProdSum
     * @apiGroup UserProfit
     *
     *  @apiParam {int} CompanyId 商户Id.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "amount": 16000,
     *                   "userBalance": 0,
     *                   "userProfit": 20000
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "title":"成功",
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/orderProd/sum"
     *  }
     */
//    @RequestMapping(value = "/api/admin/orderProd/sum")
//    public String findOrderProdSum(Long companyId) {
//        int sumPrice = 0;
//        int sumExpenses = 0;
//        int sumbalance = 0;
//        UserProfit userProfit = new UserProfit();
//        OrderProd orderProd = new OrderProd();
//        orderProd.setGoodsProviderId(companyId);
//        List<OrderProd> users = orderProdService.select(orderProd);
//        for (OrderProd op : users) {
//            Order order = orderService.selectByPK(op.getOrderId());
//            if (order.getPayStatus() == 1) {
//                if (op.getGoodsPayType() == 1) {
//                    sumPrice += op.getGoodsRealPrice() * op.getGoodsNumber();
//                } else if (op.getGoodsPayType() == 0) {
//                    if (companyService.selectByPK(op.getGoodsProviderId()).getCompanyType() == 1) {
//                        sumPrice += (op.getGoodsScreenPrice() - op.getGiveScore() * 100) * op.getGoodsNumber();
//                    } else {
//                        sumPrice += op.getGoodsRealPrice() * op.getGoodsNumber();
//                    }
//                }
//            }
//        }
//        LocalOrder localOrder = new LocalOrder();
//        localOrder.setCompanyId(companyId);
//        List<LocalOrder> localOrders = localOrderService.select(localOrder);
//        for (LocalOrder where : localOrders) {
//            sumPrice += where.getPrice() - where.getScore() * 100;
//        }
//        Company company = companyService.selectByPK(companyId);
//        UserReward userReward = new UserReward();
//        userReward.setUserId(company.getUserId());
//        userReward.setRewardType((byte) 1);
//        List<UserReward> userRewards = userRewardService.select(userReward);
//        for (UserReward where : userRewards) {
//            sumExpenses += where.getAmount();
//        }
//
//        sumbalance = walletCompanyService.selectByPK(companyId).getCompanyBalance();
//        userProfit.setAmount(sumExpenses);
//        userProfit.setUserBalance(sumbalance);
//        userProfit.setUserProfit(sumPrice);
//        MsgOut o = MsgOut.success(userProfit);
//        return this.renderJson(o);
//    }

    /**
     * @api {get} /api/admin/orderProd/excel/{companyId} 后台管理-订单管理-商家钱包-excel导出
     * @apiSampleRequest /api/admin/orderProd/excel/{companyId}
     * @apiVersion 0.1.0
     * @apiName adminOrderProdExcel
     * @apiGroup UserProfit
     *
     * @apiParam {long} CompanyId 商户ID.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/userProfit/excel/{userId}"
     *  }
     */

    @RequestMapping(value = "/api/admin/orderProd/excel/{companyId}")
    public void adminOrderProdExcel(@PathVariable("companyId") Long companyId) {
        //SHEET1
        WalletCompany company1;
        List<Company> companies = new ArrayList<>();
        company1 = walletCompanyService.selectByPK(companyId);
        Company company;
        company = companyService.selectByPK(companyId);
        company.setBankName(company1.getCompanyBalance().toString());
        company.setBankAccount(company1.getCompanyAmount().toString());
        company.setMobile(TimeUtils.getDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_LINE, company1.getCtime()));
        companies.add(company);
        //SHEET2
        UserProfit userProfit = new UserProfit();
        List<UserProfit> users;
        userProfit.setUserId(company.getUserId());
        users = userProfitService.select(userProfit);
        for (UserProfit up : users) {
            up.setRemark(TimeUtils.getDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_LINE, up.getCtime()));
            up.setConsumerId(company.getCompanyId());
            switch (up.getOrderType()) {
                case 0:
                    up.setOrderSn("商城供货商订单返利(单位：分)");
                    break;
                case 1:
                    up.setOrderSn("地面店扫码订单返利(单位：分)");
                    break;
                case 2:
                    up.setOrderSn("商城微商订单返利(单位：分)");
                    break;
                case 3:
                    up.setOrderSn("地面店扫码订单返积分");
                    break;
                case 4:
                    up.setOrderSn("商城微商订单返积分");
                    break;
            }
        }
        HttpServletResponse response = this.getResponse();
        //设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel");        //改成输出excel文件
        String fileName = company.getLinkman();
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

        //创建工作簿并发送到浏览器
        try {
            //创键Excel表格中的第一个表,命名为"第一页"
            WritableWorkbook book = Workbook.createWorkbook(response.getOutputStream());
//第一sheet
            WritableSheet sheet = book.createSheet("订单详情", 0);
            //设置该单元格的表头
            List<String> keys = new ArrayList<>();
            keys.add("公司ID");
            keys.add("公司名称");
            keys.add("公司归属人ID");
            keys.add("公司负责人");
            keys.add("账户余额");
            keys.add("账户累计总金额");
            keys.add("时间");
            // 添加标题
            for (int x = 0; x < keys.size(); x++) {
                sheet.addCell((WritableCell) new Label(x, 0, keys.get(x)));
            }
            // 添加数据
            for (int y = 0; y < companies.size(); y++) {
                sheet.addCell(new Label(0, y + 1, companies.get(y).getCompanyId().toString()));
                sheet.addCell(new Label(1, y + 1, companies.get(y).getCompanyName()));
                sheet.addCell(new Label(2, y + 1, companies.get(y).getUserId().toString()));
                sheet.addCell(new Label(3, y + 1, companies.get(y).getLinkman()));
                sheet.addCell(new Label(4, y + 1, companies.get(y).getBankName()));
                sheet.addCell(new Label(5, y + 1, companies.get(y).getBankAccount()));
                sheet.addCell(new Label(6, y + 1, companies.get(y).getMobile()));
            }
//第二个sheet
            WritableSheet sheet2 = book.createSheet("返利详情", 1);

            //设置该单元格的表头
            List<String> keys2 = new ArrayList<>();
            keys2.add("流水ID");
            keys2.add("订单ID");
            keys2.add("订单类型");
            keys2.add("收支出");
            keys2.add("账户余额");
            keys2.add("时间");
            // 添加标题
            for (int x = 0; x < keys2.size(); x++) {
                sheet2.addCell((WritableCell) new Label(x, 0, keys2.get(x)));
            }
            // 添加数据
            for (int y = 0; y < users.size(); y++) {
                sheet2.addCell(new Label(0, y + 1, users.get(y).getProfitId().toString()));
                sheet2.addCell(new Label(1, y + 1, users.get(y).getOrderId().toString()));
                sheet2.addCell(new Label(2, y + 1, users.get(y).getOrderSn()));
                sheet2.addCell(new Label(3, y + 1, users.get(y).getUserProfit().toString()));
                sheet2.addCell(new Label(4, y + 1, users.get(y).getAmount().toString()));
                sheet2.addCell(new Label(5, y + 1, users.get(y).getRemark()));
            }

            // 写入数据并关闭文件
            book.write();
            book.close();
        } catch (Exception e) {

        }
    }

}
